package com.hzeport.bgs22emduty.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class WordUtils {

    public static void generateWord(Map<String, Object> dataMap, String templateName, String fileName, String templatePath) throws IOException, TemplateException {
        Configuration configuration = new Configuration(new Version("2.3.30"));
        configuration.setDefaultEncoding("UTF-8");
        configuration.setDirectoryForTemplateLoading(new File(templatePath));
        Template tem = configuration.getTemplate(templateName, "UTF-8");
        try(Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), StandardCharsets.UTF_8));){
            tem.process(dataMap,out);
        }catch (IOException e){
            e.printStackTrace();
        }

    }

    public static void generateWord(Map<String, Object> dataMap, String templateName,  String templatePath, HttpServletResponse httpServletResponse) throws IOException, TemplateException {
        Configuration configuration = new Configuration(new Version("2.3.30"));
        configuration.setDefaultEncoding("UTF-8");
        configuration.setDirectoryForTemplateLoading(new File(templatePath));
        Template tem = configuration.getTemplate(templateName, "UTF-8");
        Writer out = new BufferedWriter(new OutputStreamWriter(httpServletResponse.getOutputStream(), StandardCharsets.UTF_8));
        tem.process(dataMap,out);
        out.flush();
        out.close();
    }


}
